<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字搜索" clearable></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="employees" highlight-current-row v-loading="listLoading"
				  @selection-change="selsChange" style="width: 100%; ">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="40">
			</el-table-column>
			<el-table-column prop="username" label="姓名" width="100" sortable>
			</el-table-column>
			<el-table-column prop="email" label="邮箱" width="160" sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话" width="120" sortable>
			</el-table-column>
			<el-table-column prop="age" label="年龄" width="80" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state == 1">启用</span>
					<span style="color: red" v-else-if="scope.row.state == 0">禁用</span>
					<span style="color: grey" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.name" label="管理部门" width="100" sortable>
			</el-table-column>
			<!--<el-table-column prop="parent.name" label="管理店铺" width="120" sortable>
			</el-table-column>-->
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
						   @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :current-page="currentPage"
						   :total="total"
						   style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面
		  employeeFormVisible 模态框是否显示
		  employeeFormRules  校验规则
		  ref="employeeForm"  给当前表单取别名  ——> refs
		-->
		<el-dialog title="新增或编辑" :visible.sync="employeeFormVisible" :close-on-click-modal="false">
			<el-form :model="employeeForm" label-width="80px"
					 :rules="employeeFormRules"
					 ref="employeeForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="employeeForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="employeeForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="employeeForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄" prop="age">
					<el-input v-model="employeeForm.age" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="employeeForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理部门">
					<!--<el-input v-model="employeeForm.manager"></el-input>-->
					<!--
                      :value="item"  可以传递一个对象过去
                       value-key="id"  通过id去找对象 然后赋值
                    -->
					<el-select v-model="employeeForm.manager" value-key="id"  placeholder="请选择" clearable>
						<el-option
								v-for="item in departments"
								:key="item.id"
								:label="item.name"
								:value="item">
							<span style="float: left">{{ item.name }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<!--<el-form-item label="父部门">
					&lt;!&ndash;<el-input v-model="employeeForm.parent"></el-input>&ndash;&gt;
					<el-cascader v-model="employeeForm.parent"
								 :options="deptTree"
								 :props="{
                               checkStrictly: true,
                               label:'name',
                               value:'id'
                             }"
								 clearable></el-cascader>
				</el-form-item>-->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="employeeFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="employeeSubmit" :loading="employeeLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    /*import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, employeeEmployee, addEmployee } from '../../api/api';
*/
    export default {
        data() {
            return {
                filters: {
                    keyword: ''
                },
                employees: [],
                total: 0,
                currentPage: 1,
                pageSize: 6,
                listLoading: false,
                sels: [],//列表选中行

                employeeFormVisible: false,//编辑界面是否显示
                employeeLoading: false,//提交按钮忙等
                employeeFormRules: {//表单校验规则
                    username: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入电话', trigger: 'blur' }
                    ]
                },
                //编辑界面数据
                employeeForm: {//表单模型数据
                    id:null,
                    username:"",
                    email:"",
                    phone:"",
                    age:null,
                    state:0,
					manager:null
                },
				// 管理部门
				departments:[],
				/*// 部门级联树
				deptTree:[]*/
            }
        },
        methods: {
            search(){//只要是高级查询按钮一点击
                this.currentPage = 1;//定位到第一页
                this.getEmployees();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.getEmployees();
            },
            //获取部门列表
            getEmployees() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;//开启忙等框
                this.$http.post("/employee",para)
                    .then(result=>{
                        result = result.data;// pageList
                        this.employees = result.rows;
                        this.total = result.total;
                        this.listLoading = false;

                    })
                    .catch(result=>{
                        alert("系统错误！");
                    })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;//开启忙等框
                    //NProgress.start();
                    this.$http.delete("/employee/"+row.id)
                        .then(result=>{
                            this.listLoading = false;//关闭忙等框
                            //???  该完成什么事情
                            result = result.data;//AjaxResult {success:true,message:"操作成功"}
                            //AjaxResult {success:false,message:"操作失败"}
                            if(result.success){
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
                                if (this.total % this.pageSize == 1){
                                    this.currentPage = this.currentPage - 1;
                                }
								this.getEmployees();
                            }else{
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(result=>{
                            console.log(result);
                            alert("系统错误！");
                        })
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.employeeForm = Object.assign({}, row);//拷贝对象（回显）
				/*this.getDeptTree();*/
				/*let dirPath = row.dirPath;
				// 需要把字符串转换为数组
				if(dirPath){
				    let tmp = [];
                    let dirPaths =  dirPath.trim().split("/"); //['','2','5','11']
                    for(let i=1;i<dirPaths.length-1;i++){
                        tmp[i-1] = parseInt(dirPaths[i]);
                    }
                    this.employeeForm.parent = tmp; //根据dirpath构造数组
				}*/
                this.employeeFormVisible = true;//显示模态框
                /*重置表单校验*/
                this.$refs['employeeForm'].resetFields();
            },
            //显示新增界面
            handleAdd: function () {
                this.employeeFormVisible = true;//显示模态框
                this.employeeForm = {//清空历史数据，不要ID
                    username:"",
                    email:"",
                    phone:"",
                    age:null,
                    state:0,
                    manager:null
					/*manager_id:null,
					parent_id:0*/
                };
                /*this.getDeptTree();*/
                /*重置表单校验*/
                this.$refs['employeeForm'].resetFields();
            },
            //编辑提交按钮
            employeeSubmit: function () {
                /*拿到当前vue里面的所有ref，从里面找到 employeeForm*/
                this.$refs.employeeForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '温馨提示', {})
                            .then(() => {
                                this.employeeLoading = true;
                                //NProgress.start();
                                //准备表单数据提交给后台
                                let para = Object.assign({}, this.employeeForm);
                                //格式转换
								/* 有可能不选，就等于新增顶级部门 */
								/*if(para.parent){
								    let arrayTmp = para.parent;
								    /!* 选择的部门只用传递最后一级 *!/
								    para.parent = {
								        id: arrayTmp[arrayTmp.length - 1]
									};
								}*/
                                this.$http.put("/employee",para)
                                    .then(result => {
                                        //关闭忙等框
                                        this.employeeLoading = false;
                                        result = result.data;
                                        if(result.success){
                                            //NProgress.done();
                                            this.$message({
                                                message: '提交成功',
                                                type: 'success'
                                            });
                                            /*重置表单校验*/
                                            this.$refs['employeeForm'].resetFields();
                                            this.employeeFormVisible = false;
                                            /*刷新页面*/
                                            this.currentPage = 1;//定位到第一页
                                            this.getEmployees();
                                        }else{
                                            this.$message({
                                                message: result.message,
                                                type: 'error'
                                            });
                                        }
                                    });
                            }).catch(result=>{
                            console.log(result);
                            alert("系统错误！");
                        });
                    }
                });
            },
            selsChange: function (sels) {
                /*现目前已经选中的所有行的数据*/
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);//[1,5]
                this.$confirm('确认删除选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;//开启忙等框
                    //NProgress.start();
                    this.$http.patch("/employee",ids)
                        .then(result=>{
                            this.listLoading = false;//关闭忙等框
                            //???  该完成什么事情
                            result = result.data;//AjaxResult {success:true,message:"操作成功"}
                            //AjaxResult {success:false,message:"操作失败"}
                            if(result.success){
                                this.$message({
                                    message: result.message,
                                    type: 'success'
                                });
                                if (this.total % this.pageSize == 1){
                                    this.currentPage = this.currentPage - 1;
                                }
                                this.getEmployees();
                            }else{
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(result=>{
                            console.log(result);
                            alert("系统错误！");
                        })
                    /*batchRemoveEmployee(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getEmployees();
                    });*/
                }).catch(() => {

                });
            },
			// 查询员工管理数据 用来渲染部门管理下拉菜单
			getDepartments(){
                this.$http.get("/dept/list",{})
					.then(result=>{
					    result = result.data;
					    this.departments = result;
					})
					.catch(result=>{
					    alert("系统错误！")
					})
			}/*,
			// 加载部门树，发送请求从后端拿数据
			getDeptTree(){
                this.$http.get("/dept/deptTree",{})
					.then(result=>{
					    result = result.data;
					    this.deptTree = result;
					})
					.catch(result=>{
					    alert("系统错误！");
					})
			}*/
        },
        mounted() {
            /*页面加载完成触发*/
            this.getEmployees();
            /!* 加载管理员信息*!/
            this.getDepartments();
        }
    }

</script>

<style scoped>

</style>